<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="
        isUpdate
          ? t('routes.demo.knowledgeManager.editLabel')
          : t('routes.demo.knowledgeManager.addLabel')
      "
      @register="register"
      @ok="handleSubmit"
      :destroyOnClose="true"
      :minHeight="400"
      :width="600"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getAddLabel } from './tableData';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { addDocLabelApi, updateDocLabelApi } from '/@/api/demo/flow';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(true);
  const useCommonStore = useUserStore();
  const labelID: any = ref('');
  const founder: any = ref('');
  const parentID: any = ref('');

  founder.value = useCommonStore.userInfo?.userId;
  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    labelID.value = data.record.labelID;
    parentID.value = data.record.parentDocLabel;
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue({ ...data.record });
    }
  });

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
    schemas: getAddLabel(),
    showActionButtonGroup: false,
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        values['labelID'] = labelID.value;
        values['parentDocLabel'] = parentID.value;
        await updateDocLabelApi(values);
      } else {
        values['founder'] = founder.value;
        values['parentDocLabel'] = labelID.value;
        await addDocLabelApi(values);
      }

      closeModal();
      emit('success');
      createMessage.success(t('common.saveSuccess'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  ::v-deep(.rc-virtual-list-scrollbar-thumb) {
    visibility: hidden !important;
  }

  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  ::v-deep(.ant-input-number) {
    width: 100% !important;
  }
</style>
